#!/bin/bash
#
#********************************************************************
#Author:                songliangcheng
#QQ:                    2192383945
#Date:                  2022-11-11
#FileName：             add-docker-proxy.sh
#URL:                   blog.mykernel.cn
#Description：          bash add-docker-proxy.sh -d --http-proxy 1; 
#                       bash add-docker-proxy.sh --http-proxy 192.168.0.111:808 --no-proxy 127.0.0.1,localhost,10.10.0.0/16,10.20.0.0/16,192.168.0.0/24,172.18.0.0/24

#Copyright (C):        2022 All rights reserved
#********************************************************************
#描述:
#--http-proxy 选项必须传递
#--no-proxy 选项可以省略
#-d 选项可以省略，且是一个flag。省略为0,添加为1

source <(curl -sSLf https://gitee.com/slcnx/tools/raw/master/parse_cmd.sh | sed 's/\r//g')

CONFIG='

key    ,argument    ,isempty    ,desc    

--http-proxy    ,_HTTP_PROXY    ,0    ,http代理

--no-proxy    ,_NO_PROXY    ,1    ,哪些IP可以不代理，给127.0.0.1,localhost追加

-d    ,    ,1    ,删除？

'

parse_cmd $@

echo $_HTTP_PROXY

: ${_NO_PROXY:=localhost,127.0.0.1}


echo "$_NO_PROXY -d state: $(getflag '-d') "



delete() {
  if [ -f /etc/systemd/system/docker.service.d/http-proxy.conf ]; then
    rm -f /etc/systemd/system/docker.service.d/http-proxy.conf
    systemctl daemon-reload
    systemctl restart docker
  fi
}

addproxy() {
  mkdir -p /etc/systemd/system/docker.service.d
  cat > /etc/systemd/system/docker.service.d/http-proxy.conf <<EOF
[Service]
Environment="HTTP_PROXY=$_HTTP_PROXY"
Environment="HTTPS_PROXY=$_HTTP_PROXY"
Environment="NO_PROXY=$_NO_PROXY"
EOF
  systemctl daemon-reload
  systemctl restart docker
}
deleteos() {
  sed -i -r '/http(s)?_proxy|ftp_proxy|no_proxy|^$/Id' /etc/environment
}

addosproxy() {
  tee -a /etc/environment <<EOF
export http_proxy="$_HTTP_PROXY"
export https_proxy="$_HTTP_PROXY"
export ftp_proxy="$_HTTP_PROXY"
export no_proxy="$_NO_PROXY"

export HTTP_PROXY="$_HTTP_PROXY"
export HTTPS_PROXY="$_HTTP_PROXY"
export FTP_PROXY="$_HTTP_PROXY"
export NO_PROXY="$_NO_PROXY"
EOF
echo 'source /etc/environment' > /etc/profile.d/environment.sh
}
# 如果是删除
if [ $(getflag '-d') -eq 1 ]; then
#  deleteos
  delete
else 
  deleteos
#  addosproxy

  delete
  addproxy
fi
